package FenxiaoService

import (
	"context"
	"gdshop-font-api-go/app/request/FenxiaoReq"
	"gdshop-font-api-go/library/response"
	"gdshop-font-api-go/library/tools"
	toolsDb "gdshop-font-api-go/library/tools/db"
	"github.com/gogf/gf/errors/gerror"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/gconv"
	"time"
)

// SubmitWithdrawApply 提交提现申请
func SubmitWithdrawApply(ctx context.Context, parames *FenxiaoReq.SubmitWithdrawApply) *response.JsonResponse {
	if !ConfigLevelConfig() {
		// 未开启分销功能，返回
		return response.FailByRequestMessage(nil, "分销功能已关闭")
	}
	config, err := GetConfig()
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	// 取出该会员可提现的金额
	xinxi := GetMemberWithdrawInfo(ctx, int(parames.MemberId))
	if parames.Money > gconv.Float64(xinxi["available_withdraw"]) {
		return response.FailByRequestMessage(nil, "可提现金额不足")
	}
	// 判断最低提现金额
	if parames.Money < (config.LowestWithdraw * 100) {
		return response.FailByRequestMessage(nil, "未达到最小提现金额")
	}

	fuModel, err := GetFenxiaoUserModelByMemberId(ctx, int(parames.MemberId))
	if err != nil {
		if gerror.Code(err) == 6000 {
			// 没有找到数据，已可能用户未加入分销
			return response.FailByRequestMessage(nil, "当前会员未加入分销")
		}
		return response.FailByRequestMessage(nil, err.Error())
	}
	withdrawNo, err := tools.GetOrderNo(3)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	//提现手续费
	handlingFee := parames.Money * config.WithdrawRate / 100
	//实际到账金额，如果小于 1 ，不允许提现
	if (parames.Money - handlingFee) < 1 {
		return response.FailByRequestMessage(nil, "实际到账金额，小于1分钱")
	}
	fwData := g.Map{
		"withdraw_no":     withdrawNo,
		"fenxiao_user_id": fuModel.Id,
		"member_id":       parames.MemberId,
		"money":           parames.Money,               //提现金额
		"rate":            config.WithdrawRate * 100,   //提现手续费率
		"handling_fee":    handlingFee,                 //提现手续费
		"amount_received": parames.Money - handlingFee, //实际到账金额
		"apply_time":      time.Now().Unix(),           //申请时间
	}

	_, err = toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "fenxiao_withdraw").InsertAndGetId(fwData)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}

	return response.SuccessByRequestMessage(nil, "成功")
}
